package com.zmx.patients.view.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.TimeQuantum;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
*时间：2020/5/26 20:38
*功能：手环数据
*/
public class BraceletDataActivity extends BaseActivity implements OnChartGestureListener, OnChartValueSelectedListener {

    private LineChart mChart, lineChart_bp, body_temperature;
    private LineData data, hrv_data, bt_data;
    private List<TimeQuantum> list_hr;
    private List<TimeQuantum> hrv;
    private List<TimeQuantum> bts;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bracelet_data;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);


        mChart = findViewById(R.id.lineChart);
        mChart.setOnChartGestureListener(this);
        mChart.setOnChartValueSelectedListener(this);
        mChart.setDrawGridBackground(false);
        // 无描述文本
        mChart.getDescription().setEnabled(false);
        // 使能点击
        mChart.setTouchEnabled(false);
        mChart.setScaleXEnabled(true);
        mChart.setScaleYEnabled(false);
        // 使能拖动和缩放
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        // 如果为false，则x，y两个方向可分别缩放
        mChart.setPinchZoom(true);


        lineChart_bp = findViewById(R.id.lineChart_bp);
        lineChart_bp.setOnChartGestureListener(this);
        lineChart_bp.setOnChartValueSelectedListener(this);
        lineChart_bp.setDrawGridBackground(false);
        // 无描述文本
        lineChart_bp.getDescription().setEnabled(false);

        // 使能点击
        lineChart_bp.setTouchEnabled(false);
        lineChart_bp.setScaleXEnabled(true);
        lineChart_bp.setScaleYEnabled(false);

        // 使能拖动和缩放
        lineChart_bp.setDragEnabled(true);
        lineChart_bp.setScaleEnabled(true);

        // 如果为false，则x，y两个方向可分别缩放
        lineChart_bp.setPinchZoom(true);


        body_temperature = findViewById(R.id.body_temperature);
        body_temperature.setOnChartGestureListener(this);
        body_temperature.setOnChartValueSelectedListener(this);
        body_temperature.setDrawGridBackground(false);
        // 无描述文本
        body_temperature.getDescription().setEnabled(false);
        // 使能点击
        body_temperature.setTouchEnabled(false);
        body_temperature.setScaleXEnabled(true);
        body_temperature.setScaleYEnabled(false);
        // 使能拖动和缩放
        body_temperature.setDragEnabled(true);
        body_temperature.setScaleEnabled(true);
        // 如果为false，则x，y两个方向可分别缩放
        body_temperature.setPinchZoom(true);

        getHr();
        getBp();
        getBt();

    }


    private LineData getData(List<TimeQuantum> tqs) {
        //设置x轴位置
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(true);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置x轴间距
        xAxis.setGranularity(1f);
//        xAxis.setLabelCount(tqs.size(),true);
        xAxis.setLabelCount(15);//一个界面显示10个Lable。那么这里要设置11个
        xAxis.setLabelRotationAngle(-30);

        // 横坐标文字
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if (tqs.size() < 3) {
                    return "";
                }

                if (value < tqs.size()) {

                    String str = tqs.get((int) value).getTime();

                    return str;

                } else {

                    return null;

                }
            }
        });

        //去除右边的y轴
        YAxis yAxisRight = mChart.getAxisRight();
        yAxisRight.setEnabled(false);
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < tqs.size(); i++) {
            // 要显示的数据
            yVals1.add(new Entry(i, Float.parseFloat(tqs.get(i).getHr() + "")));

        }

        //一条曲线对应一个LineDataSet
        LineDataSet set1 = new LineDataSet(yVals1, "心率记录值");
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置曲线为圆滑的线
        set1.setCubicIntensity(0.2f);
        set1.setValueTextSize(8f);
        set1.setDrawCircles(true);  //设置有圆点
        set1.setLineWidth(0.8f);    //设置线的宽度
        set1.setCircleSize(1f);   //设置小圆的大小

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets
        LineData data = new LineData(dataSets);

        return data;
    }


    //获取温度
    private LineData getBt_data(List<TimeQuantum> tqs) {

        //设置x轴位置
        XAxis xAxis = body_temperature.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(true);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置x轴间距
        xAxis.setGranularity(1f);
//        xAxis.setLabelCount(tqs.size(),true);
        xAxis.setLabelCount(10);//一个界面显示10个Lable。那么这里要设置11个
        xAxis.setLabelRotationAngle(-30);

        // 横坐标文字
        xAxis.setValueFormatter((value, axis) -> {


            if (tqs.size() < 3) {
                return "";
            }


            //报null
            if (value < tqs.size()) {

                String str = tqs.get((int) value).getTime();

                return str;

            } else {

                return null;

            }


        });

        //去除右边的y轴
        YAxis yAxisRight = body_temperature.getAxisRight();
        yAxisRight.setEnabled(false);

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < tqs.size(); i++) {
            // 要显示的数据
            yVals1.add(new Entry(i, Float.parseFloat(tqs.get(i).getTemp() + "")));

        }

        //一条曲线对应一个LineDataSet
        LineDataSet set1 = new LineDataSet(yVals1, "体温");
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置曲线为圆滑的线
        set1.setCubicIntensity(0.2f);
        set1.setValueTextSize(8f);
        set1.setDrawCircles(true);  //设置有圆点
        set1.setDrawValues(false);
        set1.setLineWidth(0.8f);    //设置线的宽度
        set1.setCircleSize(1f);   //设置小圆的大小

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets
        LineData data = new LineData(dataSets);

        return data;
    }

    //血压
    private LineData getBp(List<TimeQuantum> tqs) {


        //设置x轴位置
        XAxis xAxis = lineChart_bp.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(true);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置x轴间距
        xAxis.setGranularity(1f);
//        xAxis.setLabelCount(tqs.size(),true);
        xAxis.setLabelCount(13);//一个界面显示10个Lable。那么这里要设置11个
        xAxis.setLabelRotationAngle(-30);

        // 横坐标文字
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if (tqs.size() < 3) {
                    return "";
                }

                if (value < tqs.size()) {

                    String str = tqs.get((int) value).getTime();

                    return str;

                } else {

                    return null;

                }
            }
        });

        //去除右边的y轴
        YAxis yAxisRight = lineChart_bp.getAxisRight();
        yAxisRight.setEnabled(false);

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < tqs.size(); i++) {
            // 要显示的数据
            yVals1.add(new Entry(i, Float.parseFloat(tqs.get(i).getHrv() + "")));
        }

        ArrayList<Entry> yVals2 = new ArrayList<Entry>();
        for (int i = 0; i < tqs.size(); i++) {
            // 要显示的数据
            yVals2.add(new Entry(i, Float.parseFloat(tqs.get(i).getSystolic() + "")));
        }

        //一条曲线对应一个LineDataSet
        LineDataSet set1 = new LineDataSet(yVals1, "");
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置曲线为圆滑的线
        set1.setCubicIntensity(0.2f);
        set1.setValueTextSize(8f);
        set1.setDrawValues(false);
        set1.setDrawCircles(true);  //设置有圆点
        set1.setLineWidth(0.8f);    //设置线的宽度
        set1.setCircleSize(1f);   //设置小圆的大小


        //一条曲线对应一个LineDataSet
        LineDataSet set2 = new LineDataSet(yVals2, "");
        set2.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置曲线为圆滑的线
        //折线二 折线的颜色
        set2.setColor(getResources().getColor(R.color.there));
        set2.setCubicIntensity(0.2f);
        set2.setValueTextSize(8f);
        set2.setDrawValues(false);
        set2.setDrawCircles(true);  //设置有圆点
        set2.setLineWidth(1.3f);    //设置线的宽度
        set2.setCircleSize(1f);   //设置小圆的大小


        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        dataSets.add(set1); // add the datasets
        dataSets.add(set2); // add the datasets

        LineData data = new LineData(dataSets);
        return data;
    }


    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

        if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
            mChart.highlightValues(null); // or highlightTouch(null) for callback to onNothingSelected(...)
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    SimpleDateFormat sdFormatter = new SimpleDateFormat("HH:mm");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    Log.e("发顺丰", "心率数据" + msg.obj.toString());
                    list_hr = new ArrayList<>();

                    try {
                        JSONObject object = new JSONObject(msg.obj.toString());

                        JSONArray array = object.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject o = array.getJSONObject(i);

                            TimeQuantum tq = new TimeQuantum();
                            tq.setHr(o.getInt("hr"));
                            String s = sdFormatter.format(format.parse(o.getString("hrtime")));
                            tq.setTime(s);
                            list_hr.add(tq);

                        }

                        data = getData(list_hr);
                        mChart.setData(data);
                        mChart.animateX(2000);//动画时间

                    } catch (JSONException e) {
                        Log.e("发顺丰", "飞洒发" + e.toString());
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    break;


                case 2:

                    hrv = new ArrayList<>();

                    try {

                        Log.e("发顺丰", "血压" + msg.obj.toString());
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray array = object.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject o = array.getJSONObject(i);
                            TimeQuantum tq = new TimeQuantum();
                            tq.setHrv(o.getInt("systolic"));
                            tq.setSystolic(o.getInt("diastolic"));
                            String s = sdFormatter.format(format.parse(o.getString("bptime")));
                            tq.setTime(s);
                            hrv.add(tq);

                        }
                        hrv_data = getBp(hrv);
                        lineChart_bp.setData(hrv_data);
                        lineChart_bp.animateX(2000);//动画时间

                    } catch (JSONException e) {

                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    Log.e("发顺丰", "血压" + msg.obj.toString());
                    bts = new ArrayList<>();
                    try {

                        Log.e("发顺丰", "血压" + msg.obj.toString());
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray array = object.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject o = array.getJSONObject(i);
                            TimeQuantum tq = new TimeQuantum();
                            tq.setTemp(o.getInt("temp"));
                            String s = sdFormatter.format(format.parse(o.getString("bttime")));
                            tq.setTime(s);
                            bts.add(tq);

                        }
                        bt_data = getBt_data(bts);
                        body_temperature.setData(bt_data);
                        body_temperature.animateX(2000);//动画时间

                    } catch (JSONException e) {

                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }


                    break;

            }

        }
    };


    SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd");

    //获取心率数据
    public void getHr() {

        String data = formats.format(new Date());

        List<String> l = new ArrayList<>();
        l.add("865381030292617");
        l.add(data);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(this).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getHr");
        params.put("data[devicel]", "865381030292617");
        params.put("data[showtime]", data);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch/", params, handler, 1, 404);

    }

    //获取血压数据
    public void getBp() {

        String data = formats.format(new Date());

        List<String> l = new ArrayList<>();
        l.add("865381030292617");
        l.add(data);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(this).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getBp");
        params.put("data[devicel]", "865381030292617");
        params.put("data[showtime]", data);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch/", params, handler, 2, 404);

    }

    //获取血压数据
    public void getBt() {

        String data = formats.format(new Date());
        List<String> l = new ArrayList<>();
        l.add("865381030292617");
        l.add(data);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(this).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getBt");
        params.put("data[devicel]", "865381030292617");
        params.put("data[showtime]", data);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch/", params, handler, 3, 404);

    }


}
